import axios from 'axios'
import appCounst from './appCounst'
import { createStore } from '@/store'
const Store = createStore()

const netWork = {}
// 配置请求地址
const baseURL = process.env.NODE_ENV === 'production' ? appCounst.proUrl : appCounst.localUrl + appCounst.port
let reqCur = 0

// 创建axios实例
netWork.axios = axios.create({
    baseURL,
    timeout: 30000
})

// 请求拦截
netWork.axios.interceptors.request.use(function(config) {
    if (!Store.state['comcom/common'].isStopLoading) {
        Store.commit('comcom/common/SET_STATE', { loading: true })
        reqCur++
    }

    // 在发送请求之前做些什么，例如加入token
    return config
}, function(error) {
    reqCur = reqCur > 0 ? reqCur - 1 : 0
    if (reqCur === 0) {
        Store.commit('comcom/common/SET_STATE', { loading: false })
    }
    // 对请求错误做些什么
    return Promise.reject(error)
})

// 响应拦截
netWork.axios.interceptors.response.use(function(response) {
    reqCur = reqCur > 0 ? reqCur - 1 : 0
    if (reqCur === 0) {
        Store.commit('comcom/common/SET_STATE', { loading: false })
    }
    // 在接收响应做些什么，例如跳转到登录页
    return response
}, function(error) {
    reqCur = reqCur > 0 ? reqCur - 1 : 0
    if (reqCur === 0) {
        Store.commit('comcom/common/SET_STATE', { loading: false })
    }
    // 对响应错误做点什么
    return Promise.reject(error)
})

export default netWork
